<?php

class RobService
{
    /**
     * @var RobService
     */
    private static $instance;

    /**
     * Get the instance of RobService
     * @return RobService
     */
    public static function get() {
        if (!self::$instance) {
            self::$instance = new RobService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    public function __construct() {

    }

    /**
     * 获取信息
     * @param $userId
     * @return array
     * @throws SzException
     */
    public function info($userId) {
        /**
         * @var $robFlowerGrowersInfoList robFlowerGrowersInfoVoList
         * @var $robFlowerGrowersInfo robFlowerGrowersInfoVo
         * @var $robFlowerGrowersLotteryList robFlowerGrowersLotteryVoList
         * @var $robFlowerGrowersLottery robFlowerGrowersLotteryVo
         */
        $position = 1;
        $robFlowerGrowersInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ROB_FLOWER_GROWERS_INFO);
        $robFlowerGrowersInfo = $robFlowerGrowersInfoList->getElement($position,false);
        if (!$robFlowerGrowersInfo) {
            $robFlowerGrowersInfo = new RobFlowerGrowersInfoVo($userId,$position,0,0,[],true);
            $robFlowerGrowersInfoList->addElement($robFlowerGrowersInfo);
            $robFlowerGrowersInfoList->setElement($position,$robFlowerGrowersInfo);
            SzPersister::get()->setVoList($robFlowerGrowersInfoList);
        }

        $robFlowerGrowersLotteryList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ROB_FLOWER_GROWERS_LOTTERY);
        $robFlowerGrowersLottery = $robFlowerGrowersLotteryList->getElement(GameConst::INDEX_ID,false);
        if (!$robFlowerGrowersLottery) {
            $robFlowerGrowersLottery = new RobFlowerGrowersLotteryVo($userId,GameConst::INDEX_ID,0,[],0,true);
            $robFlowerGrowersLotteryList->addElement($robFlowerGrowersLottery);
            $robFlowerGrowersLotteryList->setElement(GameConst::INDEX_ID,$robFlowerGrowersLottery);
            SzPersister::get()->setVoList($robFlowerGrowersLotteryList);
        }
        /** @var ModuleProfileVo $info */
        $info = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        $targetInfo = array();
        if ($info->getTargetId()) {
            $targetInfo = ActivityService::get()->getUserInfo($info->getTargetId(),0);
        }

        $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
        $num = 0;
        foreach ($itemList->toArray() as $itemId=>$item) {
            if ($itemId == GameConst::SHIELD_ITEM_ID) {
                foreach ($item as $val) {
                    $num += $val['freeCount'];
                }
                break;
            }
        }

        $data = array();
        foreach ($robFlowerGrowersInfoList->toArray() as $k=>$v) {
            $data[$k] = $v;
            $data[$k]['info'] = array();
            if ($v['targetId']) {
                $data[$k]['info'] = ActivityService::get()->getUserInfo($v['targetId'],0);
            }
        }

        return array(
            'code' => GameConst::CODE_1000,
            'robFlowerGrowersInfo' => $data,
            'robFlowerGrowersLottery' => $robFlowerGrowersLottery->toArray(),
            'info' => $info->toArray(),
            'targetInfo' => $targetInfo,
            'num' => $num
        );
    }

    /**
     * @param $userId
     * @param $position
     * @return array
     * @throws SzException
     */
    public function unlock($userId,$position) {
        if (!$position ||$position > 3) {
            return array(
                'code' => GameConst::CODE_1030,
            );
        }
        /**
         * @var $robFlowerGrowersInfoList robFlowerGrowersInfoVoList
         * @var $robFlowerGrowersInfo robFlowerGrowersInfoVo
         */
        $robFlowerGrowersInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ROB_FLOWER_GROWERS_INFO);
        $robFlowerGrowersInfo = $robFlowerGrowersInfoList->getElement($position,false);
        if ($robFlowerGrowersInfo) {
            return array(
                'code' => GameConst::CODE_1031,
            );
        }
        if ($position > 1) {
            $lastPosition = $position - 1;
            $robFlowerGrowersInfoList->getElement($lastPosition);
        }

        $robOthersSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_OTHERS, GameConst::INDEX_ID, true);

        if($position == 2) {
            $unlockConsume = $robOthersSetting['unlockConsume1'];
        } else {
            $unlockConsume = $robOthersSetting['unlockConsume2'];
        }

        $output= '';
        foreach ($unlockConsume as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $output .= $entityId.':'.$count.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,0,$output,'unlock');//消耗资源上报

        $robFlowerGrowersInfo = new RobFlowerGrowersInfoVo($userId,$position,0,0,[],true);
        $robFlowerGrowersInfoList->addElement($robFlowerGrowersInfo);
        $robFlowerGrowersInfoList->setElement($position,$robFlowerGrowersInfo);
        SzPersister::get()->setVoList($robFlowerGrowersInfoList);
        return array(
            'code' => GameConst::CODE_1000,
        );
    }

    /**
     * 设置护盾状态
     * @param $userId
     * @param $status
     * @return array
     * @throws SzException
     */
    public function setStatus($userId,$status) {
        /**
         * @var $robFlowerGrowersLotteryList robFlowerGrowersLotteryVoList
         * @var $robFlowerGrowersLottery robFlowerGrowersLotteryVo
         */
        $robFlowerGrowersLotteryList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ROB_FLOWER_GROWERS_LOTTERY);
        $robFlowerGrowersLottery = $robFlowerGrowersLotteryList->getElement(GameConst::INDEX_ID);

        if ($status) {
            $status = 1;
        } else {
            $status = 0;
        }

        $robFlowerGrowersLottery->setStatus($status);
        $robFlowerGrowersLotteryList->updateElement(GameConst::INDEX_ID,$robFlowerGrowersLottery);
        SzPersister::get()->setVoList($robFlowerGrowersLotteryList);

        return array(
            'code' => GameConst::CODE_1000
        );
    }

    /**
     * 抓捕玩家
     * @param $userId
     * @param $targetId
     * @param $position
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function operate($userId,$targetId,$position,$reqTime) {
        if ($userId == $targetId) {
            return array(
                'code' => GameConst::CODE_1030
            );
        }

        /** @var ModuleProfileVo $profile1 */
        $profile1 = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        if($profile1->getTargetId() == $targetId && $profile1->getCoolingTime() > $reqTime) {
            return array(
                'code' => GameConst::CODE_1038
            );
        }

        $redisDb = SzDbFactory::get()->getDb($targetId, SzAbstractDb::DB_TYPE_REDIS);
        if($redisDb->get(GameConst::CACHE_ROB_KEY.$targetId)) {
            return array(
                'code' => GameConst::CODE_1032
            );
        }
        $redisDb->incr(GameConst::CACHE_ROB_KEY.$targetId);
        $redisDb->expire(GameConst::CACHE_ROB_KEY.$targetId,10);
        /** @var ModuleProfileVo $profile */
        $profile = SzPersister::get()->getVo($targetId, ModuleProfileConst::ORM_NAME_PROFILE);
        if (!$profile) {
            $redisDb->delete(GameConst::CACHE_ROB_KEY.$targetId);
            return array(
                'code' => GameConst::CODE_1032
            );
        }

        $robOthersSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_OTHERS, GameConst::INDEX_ID, true);

        if ($profile->getCoolingTime() > $reqTime) {
            $redisDb->delete(GameConst::CACHE_ROB_KEY.$targetId);
            return array(
                'code' => GameConst::CODE_1034
            );
        }

        if(($profile->getCoolingTime() + $robOthersSetting['guardTime']) > $reqTime) {
            $redisDb->delete(GameConst::CACHE_ROB_KEY.$targetId);
            return array(
                'code' => GameConst::CODE_1034
            );
        }

        /**
         * @var $robFlowerGrowersInfoList robFlowerGrowersInfoVoList
         * @var $robFlowerGrowersInfo robFlowerGrowersInfoVo
         * @var $targetRobFlowerGrowersLotteryList robFlowerGrowersLotteryVoList
         * @var $targetRobFlowerGrowersLottery robFlowerGrowersLotteryVo
         */
        $robFlowerGrowersInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ROB_FLOWER_GROWERS_INFO);
        $robFlowerGrowersInfo = $robFlowerGrowersInfoList->getElement($position);

        if($robFlowerGrowersInfo->getTargetId()) {
            $redisDb->delete(GameConst::CACHE_ROB_KEY.$targetId);
            return array(
                'code' => GameConst::CODE_1033
            );
        }

        $targetRobFlowerGrowersLotteryList = SzPersister::get()->getVoList($targetId, GameConst::ORM_NAME_ROB_FLOWER_GROWERS_LOTTERY);
        $targetRobFlowerGrowersLottery = $targetRobFlowerGrowersLotteryList->getElement(GameConst::INDEX_ID,false);
        $status = 0;
        if ($targetRobFlowerGrowersLottery) {
            $status = $targetRobFlowerGrowersLottery->getStatus();
        }


        // 消耗道具
        $output = '';
        foreach ($robOthersSetting['snatchOrder'] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $output .= $entityId.':'.$count.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,0,$output,'operate');//消耗资源上报

        $isResist = false; // 是否抵挡
        // 用户开启保护机制
        if ($status) {
            $itemList = SzPersister::get()->getVoList($targetId, ModuleItemConst::ORM_NAME_ITEM);
            foreach ($itemList->toArray() as $itemId=>$item) {
                if ($itemId == GameConst::SHIELD_ITEM_ID) {
                    $isResist = true;
                    break;
                }
            }
            if ($isResist) {
                $entityId = EntityService::get()->buildEntityId(GameConst::ENTITY_ACTION_CONSUME,GameConst::ENTITY_TYPE_ITEM,GameConst::SHIELD_ITEM_ID);
                GameService::get()->handleEntity($targetId, $entityId, 1, true);
                CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$targetId,0,$entityId.':1|','operate');//消耗资源上报

                $robOthersSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_OTHERS, GameConst::INDEX_ID, true)['compensationNum'];
                GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_GET_TOKEN, $robOthersSetting['721111000001'], true);
                CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,1,GameConst::ENTITY_ACTION_GET_TOKEN.':'.$robOthersSetting['721111000001'].'|','operate');//获得资源上报
            }
        }

        $success = 0;
        // 未开启保护机制
        if(!$isResist) {
            $rate = $robOthersSetting['successRate'];
            $num = mt_rand(1,100);
            if ($num <= $rate) {
                $coolingTime = $robOthersSetting['prisonTime'] + $reqTime;
                $robFlowerGrowersInfo->setReward($robOthersSetting['petalGain']);
                $robFlowerGrowersInfo->setTargetId($targetId);
                $robFlowerGrowersInfo->setCoolingTime($coolingTime);
                $robFlowerGrowersInfoList->updateElement($position,$robFlowerGrowersInfo);
                SzPersister::get()->setVoList($robFlowerGrowersInfoList);
                $profile->setTargetId($userId);
                $profile->setCoolingTime($coolingTime);
                SzPersister::get()->setVo($profile);
                $redisDb->hSet(GameConst::CACHE_ROB_ENEMY_KEY.$targetId,$userId,$reqTime);
                $success = 1;
            }
        }

        $message = array(
            'isResist' => $isResist, // 是否抵挡
            'targetId' => $userId,
            'success' => $success,
            'reqTime' => $reqTime
        );

        $redisDb->lTrim(GameConst::CACHE_KEY_ROB_SOCIAL_MESSAGE_LIST.$targetId,0,99);
        $redisDb->lPush(GameConst::CACHE_KEY_ROB_SOCIAL_MESSAGE_LIST.$targetId,json_encode($message,true));
        $redisDb->delete(GameConst::CACHE_ROB_KEY.$targetId);

        // 更新活动任务进度
        if ($success){
            $activityData = ActivityService::get()->getActivityIdAndPosition($userId,GameConst::ACTIVITY_TASK_4);
            if (!empty($activityData)){
                ActivityTaskService::get()->updateActivityTaskProgress($userId,$activityData['aid'],$activityData['position']);
            }

            // 更新合约任务进度
            $contractData = ContractService::get()->getContractOpenAndTask($userId,GameConst::CONTRACT_TASK_6,$reqTime);
            if (!empty($contractData) && !empty($contractData['task']) && !empty($contractData['session'])){
                if ($reqTime >= $contractData['start'] && $reqTime <= $contractData['end']){
                    ContractService::get()->updateTaskProgress($userId,$contractData['session'],$contractData['task']['pos'],$contractData['task']['taskId'],$reqTime);
                }
            }

            //社团竞赛任务进度添加
            UnionCompetitionService::get()->addCompetitionTaskProcess($userId,GameConst::UNION_COMPETITION_TASK_8, $reqTime,1);
        }

        return array(
            'code' => GameConst::CODE_1000,
            'message' => array(
                'isResist' => $isResist, // 是否抵挡
                'targetId' => $targetId,
                'success' => $success,
                'reqTime' => $reqTime
            )
        );
    }

    /**
     * 消息列表
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function message($userId,$reqTime) {
        $redisDb = SzDbFactory::get()->getDb($userId, SzAbstractDb::DB_TYPE_REDIS);
        $list = $redisDb->lRange(GameConst::CACHE_KEY_ROB_SOCIAL_MESSAGE_LIST.$userId,0,-1);
        $data = array();
        if ($list) {
            foreach ($list as $key => $val) {
                $val = json_decode($val,true);
                if ($val['reqTime'] < ($reqTime - GameConst::SOCIAL_VALID_TIME)) {
                    continue;
                }
                /** @var ModuleProfileVo $profile */
                $profile = SzPersister::get()->getVo($val['targetId'], ModuleProfileConst::ORM_NAME_PROFILE);
                if(!$profile) {
                    continue;
                }
                $data[$key] = ActivityService::get()->getUserInfo($val['targetId'],0);
                $data[$key]['reqTime'] = $val['reqTime'];
                $data[$key]['success'] = $val['success'];
                $data[$key]['isResist'] = $val['isResist'] ? 1 : 0;
                $data[$key]['coolingTime'] = $profile->getCoolingTime();
            }
        }

        return array(
            'data' => $data,
            'code' => GameConst::CODE_1000,
        );
    }

    /**
     * 领取奖励
     * @param $userId
     * @param $position
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function reward($userId,$position,$reqTime) {
        $robInsetSettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_INSET, null, true);
        $idList = array();
        foreach ($robInsetSettings as $key => $robInsetSetting) {
            $idList[$key] = $robInsetSetting['weights'];
        }
        $id = SzUtility::getRandomElementByProbability($idList);
        if (is_null($id)) {
            return array(
                'code' => GameConst::CODE_9999,
            );
        }

        list($min,$max) = $robInsetSettings[$id]['gainsBonus'];
        $gainsBonus = mt_rand($min,$max);

        /**
         * @var $robFlowerGrowersInfoList robFlowerGrowersInfoVoList
         * @var $robFlowerGrowersInfo robFlowerGrowersInfoVo
         * @var $targetRobFlowerGrowersLotteryList robFlowerGrowersLotteryVoList
         * @var $targetRobFlowerGrowersLottery robFlowerGrowersLotteryVo
         */
        $robFlowerGrowersInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ROB_FLOWER_GROWERS_INFO);
        $robFlowerGrowersInfo = $robFlowerGrowersInfoList->getElement($position);

        if ($robFlowerGrowersInfo->getCoolingTime() > $reqTime) {
            return array(
                'code' => GameConst::CODE_1037,
            );
        }

        $input = '';
        foreach ($robFlowerGrowersInfo->getRawReward() as $entityId => $count) {
            $count = intval($count * $gainsBonus / 100);
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $input .= $entityId.':'.$count.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,1,$input,'reward');//获得资源上报

        $robFlowerGrowersInfo->setCoolingTime(0);
        $robFlowerGrowersInfo->setTargetId(0);
        $robFlowerGrowersInfo->setReward(array());

        $robFlowerGrowersInfoList->updateElement($position,$robFlowerGrowersInfo);
        SzPersister::get()->setVoList($robFlowerGrowersInfoList);

        return array(
            'code' => GameConst::CODE_1000,
            'gainsBonus' => $gainsBonus,
            'id' => $id
        );
    }

    /**
     * 兑换
     * @param $userId
     * @return array
     * @throws SzException
     */
    public function exchange($userId) {
        /**
         * @var $robFlowerGrowersLotteryList robFlowerGrowersLotteryVoList
         * @var $robFlowerGrowersLottery robFlowerGrowersLotteryVo
         */
        $robFlowerGrowersLotteryList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ROB_FLOWER_GROWERS_LOTTERY);
        $robFlowerGrowersLottery = $robFlowerGrowersLotteryList->getElement(GameConst::INDEX_ID);

        $robOthersSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_OTHERS, GameConst::INDEX_ID, true);
        $robRewardSettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_REWARD, null, true);

        $number = $robFlowerGrowersLottery->getNumber();
        $number++;

        $firstRule = $robOthersSetting['firstRule'];
        if (in_array($number,$firstRule)) {
            $id = $this->getExchangeId($robRewardSettings,2);
        } else {
            $hiddenRule = $robOthersSetting['hiddenRule'];
            $type = 1;
            if ($hiddenRule) {
                foreach ($hiddenRule as $value) {
                    if (!($number % $value)) {
                        $type = 2;
                        break;
                    }
                }
            }
            $id = $this->getExchangeId($robRewardSettings,$type);
        }

        if (is_null($id)) {
            return array(
                'code' => GameConst::CODE_9999,
            );
        }

        $robRewardSetting = $robRewardSettings[$id];

        // 消耗道具
        $output = $input = '';
        foreach ($robOthersSetting['petalConsume'] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $output .= $entityId.':'.$count.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,0,$output,'exchange');//消耗资源上报

        foreach ($robRewardSetting['reward'] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $input .= $entityId.':'.$count.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,1,$input,'exchange');//获得资源上报

        $robFlowerGrowersLottery->setNumber($number);
        $robFlowerGrowersLotteryList->updateElement(GameConst::INDEX_ID, $robFlowerGrowersLottery);
        SzPersister::get()->setVoList($robFlowerGrowersLotteryList);

        return array(
            'code' => GameConst::CODE_1000,
            'id' => $id
        );
    }

    /**
     * @param $userId
     * @param $type
     * @param $indexId
     * @return array
     */
    public function buy($userId,$type,$indexId) {
        $robOthersSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_OTHERS, GameConst::INDEX_ID, true);
        if ($type == 1) {
            if (!isset($robOthersSetting['shieldCost'][$indexId]) || !isset($robOthersSetting['shieldCost'][$indexId])) {
                return array(
                    'code' => GameConst::CODE_1030
                );
            }
            $get = $robOthersSetting['shieldNum'][$indexId];
            $cost = $robOthersSetting['shieldCost'][$indexId];
        } else {
            if (!isset($robOthersSetting['tokenNum'][$indexId]) || !isset($robOthersSetting['tokenCost'][$indexId])) {
                return array(
                    'code' => GameConst::CODE_1030
                );
            }
            $get = $robOthersSetting['tokenNum'][$indexId];
            $cost = $robOthersSetting['tokenCost'][$indexId];
        }

        // 消耗道具
        $output = $input = '';
        foreach ($cost as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $output .= $entityId.':'.$count.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,0,$output,'buy');//消耗资源上报

        foreach ($get as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $input .= $entityId.':'.$count.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,1,$input,'buy');//获得资源上报

        return array(
            'code' => GameConst::CODE_1000,
        );
    }

    /**
     * 获取好友列表
     * @param $userId
     * @param $start
     * @param $end
     * @return array
     * @throws SzException
     */
    public function getFriendList($userId,$start,$end) {
        $info = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        /**
         * @var $friendList NewFriendsVoList
         */
        $friendList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_NEW_FRIEND);
        $count = count($friendList->getList());
        if (!$friendList || $end < $start || $start < 1 || $end < 1) {
            return array(
                'count' => $count,
                'friendList' => array()
            );
        }
        $result = array();
        $i = 1;
        foreach ($friendList->toArray() as $friendId=>$val) {
            if ($i > $end) {
                break;
            }
            /** @var ModuleProfileVo $profile */
            $profile = SzPersister::get()->getVo($friendId, ModuleProfileConst::ORM_NAME_PROFILE);
            if (!$profile) {
                $friendList->deleteElement($friendId,false);
                continue;
            }
            if ($i >= $start) {
                $result[$friendId] = ActivityService::get()->getUserInfo($friendId,0);
                $result[$friendId]['coolingTime'] = $profile->getCoolingTime();
            }
            $i++;
        }
        SzPersister::get()->setVoList($friendList);
        return array(
            'count' => $count,
            'friendList' => $result,
            'code' => GameConst::CODE_1000,
            'info' => $info->toArray()
        );
    }

    /**
     * 获取冤家列表
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getEnemyList($userId,$reqTime) {
        $info = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        $redisDb = SzDbFactory::get()->getDb($userId, SzAbstractDb::DB_TYPE_REDIS);
        $data = $redisDb->hGetAll(GameConst::CACHE_ROB_ENEMY_KEY.$userId);
        $result = array();
        if($data) {
            foreach ($data as $uid=>$time) {
                /** @var ModuleProfileVo $profile */
                $profile = SzPersister::get()->getVo($uid, ModuleProfileConst::ORM_NAME_PROFILE);
                if (!$profile || ($time < ($reqTime - GameConst::SOCIAL_VALID_TIME))) {
                    $redisDb->hDel(GameConst::CACHE_ROB_ENEMY_KEY.$userId,$uid);
                    continue;
                }
                $result[$uid] = ActivityService::get()->getUserInfo($uid,0);
                $result[$uid]['coolingTime'] = $profile->getCoolingTime();
            }
        }
        return array(
            'enemyList' => $result,
            'code' => GameConst::CODE_1000,
            'info' => $info->toArray()
        );
    }

    /**
     * 获取推荐列表
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getRecommendList($userId,$reqTime) {
        $sysConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_SYSTEM_UNLOCK, GameConst::FUNC_ROB, true);
        $level = $sysConfig['level'];

        $info = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        $listCount = 12;
        // 数据库的分库中随机取出一个shareId，然后
        $serversConfig = SzConfig::get()->loadAppConfig('database', 'MySql');
        $shardId = mt_rand(0, count($serversConfig) - 1);

        $instance = new SzMySqlDb($serversConfig[$shardId]);

        $robOthersSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_OTHERS, GameConst::INDEX_ID, true);

        $reqTime = $reqTime - $robOthersSetting['guardTime'];

        $moduleProfiles = $instance->select("SELECT `userId` FROM `module_profile` WHERE `userId` != {$userId} and `coolingTime` < {$reqTime} and `level` > {$level} ORDER BY `lastLoginTime` DESC limit " . ($listCount * 100));
        shuffle($moduleProfiles);
        $result = [];

        foreach ($moduleProfiles as $profile) {
            $uid = $profile['userId'];
            $result[$uid] = ActivityService::get()->getUserInfo($uid,0);
            if (count($result) >= $listCount) {
                break;
            }
        }

        return array(
            'recommendList' => $result,
            'code' => GameConst::CODE_1000,
            'info' => $info->toArray()
        );
    }

    /**
     * @param $robRewardSettings
     * @param $type
     * @return int|string
     */
    public function getExchangeId($robRewardSettings,$type) {
        $idList = array();
        foreach ($robRewardSettings as $id=>$robRewardSetting) {
            if ($type == 2 && $robRewardSetting['type'] == 2) {
                continue;
            }
            $idList[$id] = $robRewardSetting['weights'];
        }

        $id = SzUtility::getRandomElementByProbability($idList);

        return $id;
    }

    /**
     * @param $userId
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function dailyReward($userId,$reqTime) {
        /**
         * @var $profileInfoList  ModuleProfileInfoVoList
         * @var ModuleProfileInfoVo $robProfileInfo
         */
        $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
        $robProfileInfo = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_ROB, false);
        if (!$robProfileInfo) {
            $robProfileInfo = new ModuleProfileInfoVo(
                $userId,
                GameConst::USER_INFO_TYPE_ROB,
                0,
                $reqTime,
                true
            );
        }

        // 日期 不一致
        if(SzTime::getDate($robProfileInfo->getInfo()) == SzTime::getDate($reqTime)) {
            return false;
        }

        $input = '';
        $robOthersSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ROB_OTHERS, GameConst::INDEX_ID, true);
        foreach ($robOthersSetting['everydayOrder'] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $input .= $entityId.':'.$count.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_ROB,$userId,1,$input,'dailyReward');//获得资源上报

        $robProfileInfo->setInfo($reqTime);
        if ($robProfileInfo->isInsert() && !SzUtility::checkArrayKey(GameConst::USER_INFO_TYPE_ROB, $profileInfoList->getList())) {
            $profileInfoList->addElement($robProfileInfo);
            $profileInfoList->setElement(GameConst::USER_INFO_TYPE_ROB,$robProfileInfo);
        } else {
            $profileInfoList->updateElement(GameConst::USER_INFO_TYPE_ROB,$robProfileInfo);
        }
        SzPersister::get()->setVoList($profileInfoList);
        return true;
    }
}